using Autofac;
using Autofac.Extras.DynamicProxy;
using System;
using System.Reflection;

namespace JGSY.Autofac.AOP
{
    class Program
    {
        static void Main(string[] args)
        {
            //SingleAop();

            //MoreAopthisAssembly();

            var builder = new ContainerBuilder();

            // 注册拦截器
            builder.RegisterType<LoggingInterceptor>();

            // 定义需要扫描的程序集列表
            var assemblies = new List<Assembly>
            {
                Assembly.GetExecutingAssembly(),
                // 添加其他需要扫描的程序集
                // typeof(OtherNamespace.SomeService).Assembly
            };

            // 批量注册多个程序集中的服务并应用拦截器
            builder.RegisterAssemblyTypes(assemblies.ToArray())
                .Where(t => t.Name.EndsWith("Service"))
                .AsImplementedInterfaces()
                .EnableInterfaceInterceptors()
                .InterceptedBy(typeof(LoggingInterceptor));

            using (var container = builder.Build())
            {
                var orderService = container.Resolve<IOrderService>();
                orderService.CreateOrder("12345");
            }


            Console.ReadLine();
        }

        private static void MoreAopthisAssembly()
        {
            var builder = new ContainerBuilder();

            // 注册拦截器
            builder.RegisterType<LoggingInterceptor>();

            // 批量注册服务并应用拦截器
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .Where(t => t.Name.EndsWith("Service"))
                .AsImplementedInterfaces()
                .EnableInterfaceInterceptors()
                .InterceptedBy(typeof(LoggingInterceptor));

            using (var container = builder.Build())
            {
                var orderService = container.Resolve<IOrderService>();
                orderService.CreateOrder("12345");
            }
        }

        private static void SingleAop()
        {
            var builder = new ContainerBuilder();

            // 注册拦截器
            builder.RegisterType<LoggingInterceptor>();

            // 注册服务并启用AOP
            builder.RegisterType<OrderService>()
                .As<IOrderService>()
                .EnableInterfaceInterceptors()
                .InterceptedBy(typeof(LoggingInterceptor));

            using (var container = builder.Build())
            {
                var orderService = container.Resolve<IOrderService>();
                orderService.CreateOrder("12345");
            }
        }
    }
}    